package org.gap.wizards.items;

import org.gap.wizards.creature.Creature;
import org.gap.wizards.effects.Effect;
import org.gap.wizards.items.effects.Uses;
import org.gap.wizards.utils.Persistence;
import org.gap.wizards.views.ViewPlatform;

public class Item {
	private static final String CLASS = "class";
	private static final String DESCRIPTION_SECTION = "description";
	private static final String EFFECT_SECTION = "effect";
	private Effect effect;
	private Description description;
	private Uses uses = Uses.Unlimited;

	public Item(Effect effect, Description description) {
		this.effect = effect;
		this.description = description;
	}

	/**
	 * Used for loading from save.
	 */
	public Item() {
	}

	public void draw(ViewPlatform console, int x, int y) {
		description.print(console, x, y);
	}

	public String getName() {
		return description.name();
	}

	public boolean isEquipable() {
		return description.canBeEquiped();
	}
	
	public void applyAffectsOn(Creature creature) {
		effect.apply(creature);
		uses.useItem();
	}

	public boolean isConsumed() {
		return !uses.hasAvailableUses();
	}

	public void setUses(Uses uses) {
		this.uses = uses;
	}

	public void persist(Persistence persister) {
		persister.beginSection(DESCRIPTION_SECTION);
		{
			description.persist(persister);
		}
		persister.endSection();

		persister.beginSection(EFFECT_SECTION);
		{
			persister.set(CLASS, effect.getClass());
			effect.persist(persister);
		}
		persister.endSection();
	}

	public void load(Persistence persister) {
		persister.beginSection(DESCRIPTION_SECTION);
		{
			description = Description.load(persister);
		}
		persister.endSection();

		persister.beginSection(EFFECT_SECTION);
		{
			if (persister.getString(CLASS).equals(Effect.NONE.getClass().getName())) {
				effect = Effect.NONE; 
			} else {
				effect = (Effect)persister.getClass(CLASS);
				effect.load(persister);
			}
		}
		persister.endSection();
	}

	@Override
	public boolean equals(Object obj) {
		if (obj == null) {
			return false;
		}
		if (!(obj instanceof Item)) {
			return false;
		}
		Item other = (Item) obj;
		return description.equals(other.description) && effect.equals(other.effect);
	}

	@Override
	public String toString() {
		return description.name();
	}
}
